package com.ajavaer.framework.generator.reader;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;

public class PoiWordTools {

    public static XWPFDocument read(File file) throws IOException {
        try (InputStream is = new FileInputStream(file)) {
            return new XWPFDocument(is);
        }
    }

    public static void close(XWPFDocument docx) throws IOException {
        if (docx != null) {
            docx.close();
        }
    }

    public static void setCellWidth(XWPFTableCell cell, Integer width) {
        CTTc cttc = cell.getCTTc();
        CTTcPr cellPr = cttc.getTcPr() == null ? cttc.addNewTcPr() : cttc.getTcPr();
        CTTblWidth tblWidth = cellPr.isSetTcW() ? cellPr.getTcW() : cellPr.addNewTcW();
        if (width != null && width > 0) {
            tblWidth.setW(BigInteger.valueOf(width));
            tblWidth.setType(STTblWidth.DXA);
        }
    }

    public static void setCellVAlign(XWPFTableCell cell, STVerticalJc.Enum typeEnum, STJc.Enum vAlign) {
        setCellWidthAndVAlign(cell, 0, typeEnum, vAlign);
    }

    public static void setCellWidthAndVAlign(XWPFTableCell cell, Integer width, STVerticalJc.Enum typeEnum, STJc.Enum vAlign) {
        CTTc cttc = cell.getCTTc();
        CTTcPr cellPr = cttc.getTcPr();
        cellPr.addNewVAlign().setVal(typeEnum);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(vAlign);
        setCellWidth(cell, width);
    }
}
